<?php

include_once("includes/global.php");
include_once("includes/smarty_config.php");
include_once("config/reg_config.php");
include_once("config/connect_config.php");//connect
$config = array_merge($config,$reg_config);
$config = array_merge($config,$connect_config);
$connect_id = (int) $_GET['connect_id'];

if($_POST['action'] == 'mobile_submit'){
    $mobile = $_POST['mobile'];
    $connect_id =  $_POST['connect_id'];
    $code =  $_POST['code'];
    if($_SESSION['sms_code'] != $code){
        msg('oauth.php?connect_id='.$connect_id,'短信验证码不正确');
        return false;
    }
//    if($_SESSION['connect_id'] != $connect_id) {
//        msg('oauth.php?connect_id='.$_SESSION['connect_id'],'注册用户已被篡改,请重新提交');
//        return false;
//    }
    $db->query("select * from ".USERCOON." where id = ".$connect_id);
    $coon_info = $db->fetchRow();

    $sql = "select * from ".MEMBER." where user = '$mobile' or mobile = '$mobile'  ";
    $db->query($sql);
    $member_info = $db->fetchRow();
    if(empty($member_info)) {
        $regtime = date('Y-m-d H:m:s',time());
        $lastLoginTime = time();
        $ip = getip();
        $insert_sql = "insert into ".MEMBER." (`user`,`name`,`sex`,`mobile`,`logo`,`ip`,`statu`,`regtime`,`lastLoginTime`) values (
        '$mobile','{$coon_info['nickname']}','{$coon_info['gender']}','$mobile','{$coon_info['figureurl']}','$ip','2','$regtime','$lastLoginTime'
        )";
        $db->query($insert_sql);
        $last_uid = $db->lastid();
        $sql="update ".USERCOON." set userid='$last_uid' where id='$connect_id'";
        $db->query($sql);
        login($last_uid,$coon_info['nickname']);
        $forward = $post['forward']?$post['forward']:$config["weburl"]."/main.php";
        msg($forward);
    } else {
        $sql="update ".USERCOON." set userid='{$member_info['userid']}' where id='$connect_id'";
        $db->query($sql);
        login($member_info['userid'],$coon_info['nickname']);
        $forward = $post['forward']?$post['forward']:$config["weburl"]."/main.php";
        msg($forward);
    }

}


if($config['sina_connect']==1 && $_GET['type'] == 'sina' && !empty($_GET['code']))//sina
{
    define( "WB_AKEY" , $config['sina_app_id'] );
    define( "WB_SKEY" , $config['sina_key'] );
    define( "WB_CALLBACK_URL" , "$config[weburl]/oauth.php?type=sina" );
    include_once( 'includes/saetv2.ex.class.php' );
    $o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
    //------------------------------------------

    if($_GET['type']=='sina'&&isset($_REQUEST['code']))
    {
        $keys = array();
        $keys['code'] = $_REQUEST['code'];
        $keys['redirect_uri'] = WB_CALLBACK_URL;
        $token = $o->getAccessToken( 'code', $keys ) ;
        $c = new SaeTClientV2( WB_AKEY , WB_SKEY , $token['access_token'] );
        $uid_get = $c->get_uid();
        $uid = $uid_get['uid'];
        $ar = $c->show_user_by_id($uid);//IDȡûȻϢ
        //------------
        $sql="select * from ".USERCOON." where type=2 and client_id='$ar[id]'";
        $db->query($sql);
        $cre=$db->fetchRow();
        if(empty($cre['id']))
        {
            $sql="insert into ".USERCOON."
			(nickname,figureurl,gender,type,access_token,client_id)
			values
			('$ar[name]','$ar[profile_image_url]','$ar[gender]',2,'$token[access_token]','$ar[id]')";
            $db->query($sql);
            $cre['id']=$db->lastid();
        }
        if($cre['userid'])
        {//Ѿ󶨣ת¼
            login($cre['userid'],NULL);
            $forward = $post['forward']?$post['forward']:$config["weburl"]."/main.php";
            msg($forward);
        }
        else
        {//а󶨡
            $_SESSION['connect_id'] = $cre[id];
            msg("oauth.php?connect_id=$cre[id]");

        }
    }

}
if(!empty($_GET['code'])&&$config['qq_connect']==1&&$_GET['type']=='qq')//QQ
{
	
    //-----------------
    $config['return']=$config['weburl'].'/oauth.php';
    $url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
        ."client_id=$config[qq_app_id]"
        ."&client_secret=$config[qq_key]"
        ."&code=$_GET[code]"
        ."&state=$config[company]"
        ."&redirect_uri=$config[return]";
    $takenid=get_url_contents($url);
    //----------------
    $url2="https://graph.qq.com/oauth2.0/me?$takenid";
    $con=get_url_contents($url2);
    $lpos = strpos($con, "(");
    $rpos = strrpos($con, ")");
    $con  = substr($con, $lpos + 1, $rpos - $lpos -1);
    $ar2=json_decode($con,true);
    //----------------
    $url3 = "https://graph.qq.com/user/get_user_info?"
        . $takenid
        . "&oauth_consumer_key=" . $config['qq_app_id']
        . "&openid=" . $ar2["openid"]
        . "&format=json";
    $con=get_url_contents($url3);
    $ar=json_decode($con,true);
    //--------------------------
    $sql="select * from ".USERCOON." where type=1 and openid='$ar2[openid]'";
    $db->query($sql);
    $cre=$db->fetchRow();
    if(empty($cre['id']))
    {
        $sql="insert into ".USERCOON."
		(nickname,figureurl,gender,vip,level,type,access_token,client_id,openid)
		values
		('$ar[nickname]','$ar[figureurl]','$ar[gender]','$ar[vip]','$ar[level]',1,'$takenid','$ar2[client_id]','$ar2[openid]')";
        $db->query($sql);
        $cre['id']=$db->lastid();
    }
    if($cre['userid'])
    {//Ѿ󶨣ת¼
        login($cre['userid'],NULL);
        $forward = $post['forward']?$post['forward']:$config["weburl"]."/main.php";
        msg($forward);
    }
    else
    {//а󶨡
        $_SESSION['connect_id'] = $cre[id];
        msg("oauth.php?connect_id=$cre[id]");
    }

}
//=========================================== 微信快捷登录扫码===========================
if(!empty($_GET['code'])&&!empty($_GET['state'])){

    if($_GET['state'] != md5($_SESSION['wx_state'])){
        msg('login.php','state参数不正确');
        return false;
    }
    $code = $_GET['code'];


    if(empty(bgetcookie('access_token'))){
        //获取access_token
        $at_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx67c294e070463455&secret=7dde954e192dd39c48b1c947bb4213f1&code=".$code."&grant_type=authorization_code";
        $at_result=json_decode(get_url_contents($at_url),true);
        if(!empty($at_result['errcode'])){
            msg('login.php','获取access_token出错:'.$at_result['errmsg']);
            return false;
        }
        $access_token = $at_result['access_token'];
        $openid = $at_result['openid'];
        bsetcookie('access_token',$at_result['access_token'],$at_result['expires_in']);
        bsetcookie('openid',$at_result['openid'],$at_result['expires_in']);
    } else {
        $access_token = bgetcookie('access_token');
        $openid = bgetcookie('openid');
    }

    //获取用户详情
    $user_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid;
    $user_info = json_decode(get_url_contents($user_url),true);

    //--------------------------
    $sql="select * from ".USERCOON." where type=3 and openid='$user_info[openid]'";
    $db->query($sql);
    $cre=$db->fetchRow();


    if(empty($cre['id']))
    {
        $sql="insert into ".USERCOON."
		(nickname,figureurl,gender,`type`,openid)
		values
		('$user_info[nickname]','$user_info[headimgurl]','$user_info[sex]',3,'$user_info[openid]')";
        $db->query($sql);
        $cre['id']=$db->lastid();
    }
    if($cre['userid'])
    {
        login($cre['userid'],$user_info['nickname']);
        $forward = $post['forward']?$post['forward']:$config["weburl"]."/main.php";
        msg($forward);
    }
    else
    {//а󶨡
        $_SESSION['connect_id'] = $cre[id];
        msg("oauth.php?connect_id=$cre[id]");
    }

}
//=======================================支付宝登录=============================
if(!empty($_GET['token']) && $_GET['is_success'] == 'T'){
    require_once("lib/alilogin/alipay.config.php");
    require_once("lib/alilogin/lib/alipay_notify.class.php");
    //计算得出通知验证结果
    $alipayNotify = new AlipayNotify($alipay_config);
    $verify_result = $alipayNotify->verifyReturn();
    if($verify_result) {//验证成功
        $user_id = $_GET['user_id'];
        //授权令牌
        $token = $_GET['token'];

        $sql="select * from ".USERCOON." where type=4 and client_id='$user_id'";
        $db->query($sql);
        $cre=$db->fetchRow();
        if(empty($cre['id']))
        {
            $sql="insert into ".USERCOON."
		(client_id,access_token,`type`)
		values
		('$user_id','$token','4')";
            $db->query($sql);
            $cre['id']=$db->lastid();
        }
        if($cre['userid'])
        {
            login($cre['userid'],$cre['nickname']);
            $forward = $post['forward']?$post['forward']:$config["weburl"]."/main.php";
            msg($forward);
        }
        else
        {//а󶨡
            $_SESSION['connect_id'] = $cre[id];
            msg("oauth.php?connect_id=$cre[id]");
        }



    }
    else {
            msg('login.php','验证失败，请重新登录');
    }

}

//================================================
function login($uid,$username,$pid=NULL)
{
    global $post,$config;
    $db=new dba($config['dbhost'],$config['dbuser'],$config['dbpass'],$config['dbname'],$config['dbport']);
    if($uid)
        $sql="select lastLoginTime,userid,user,regtime,statu from ".MEMBER." a where a.userid='$uid'";
    else
        $sql="select lastLoginTime,userid,user,regtime,statu from ".MEMBER." where user='$username'";
    $db->query($sql);
    $re=$db->fetchRow();

    bsetcookie("USERID","$uid\t$re[user]\t$pid",NULL,"/",$config['baseurl']);
    setcookie("USER",$re['user'],NULL,"/",$config['baseurl']);
    $_SESSION["STATU"]=$re['statu'];

    $sql="update ".MEMBER." set lastLoginTime='".time()."' WHERE userid='$uid'";
    $db->query($sql);
    //--------------------------------------󶨡
    if(!empty($_GET['connect_id']*1))
    {
        $sql="update ".USERCOON." set userid='$uid' where id='$_GET[connect_id]'";
        $db->query($sql);
    }
}
function do_post($url, $data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, $url);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}
function get_url_contents($url)
{
    if(ini_get("allow_url_fopen") == "1")
        return file_get_contents($url);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result =  curl_exec($ch);
    curl_close($ch);
    return $result;
}


//================================================
$tpl->assign('connect_id',$connect_id);
include_once("footer.php");
$tpl->display("oauth.htm");
?>